package org.example.viteVantDemo.ctrl.anno;

import lombok.extern.slf4j.Slf4j;
import org.example.viteVantDemo.cache.ITokenService;
import org.example.viteVantDemo.constants.CS;
import org.example.viteVantDemo.exception.BizException;
import org.example.viteVantDemo.model.ApiRes;
import org.example.viteVantDemo.security.VantUser;
import org.example.viteVantDemo.security.VantUserDetails;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/anon")
public class AuthController {

    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public ApiRes login(@RequestBody VantUser vantUser) {
        UsernamePasswordAuthenticationToken upToken =
                new UsernamePasswordAuthenticationToken(vantUser.getUsername(), vantUser.getPassword());
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(upToken);
        } catch (BadCredentialsException e) {
            throw new BizException("用户名/密码错误！");
        } catch (AuthenticationException e) {
            log.error("AuthenticationException:", e);
            throw new BizException("认证服务出现异常， 请重试或联系系统管理员！");
        }
        VantUserDetails userDetails = (VantUserDetails) authentication.getPrincipal();
        String accessToken = CS.getCacheKeyToken(fastUUID());
        ITokenService.processTokenCache(userDetails, accessToken); //处理token 缓存信息
        UsernamePasswordAuthenticationToken authenticationRest = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationRest);

        Map<String, String> map = new HashMap<>();
        map.put(CS.ACCESS_TOKEN_NAME, accessToken);
        return ApiRes.ok(map);
    }

    public static String fastUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}

